/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[TestThreadLocal.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package api.lang;

import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * java.lang.ThreadLocal测试
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class TestThreadLocal {

	// 为每一个线程构建一个SimpleDateFormat的实例
	public static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd");
		};
	};

	// 为每一个线程构建一个随机数生成器
	public static final ThreadLocal<Random> random = new ThreadLocal<Random>() {
		@Override
		protected Random initialValue() {
			return new Random();
		};
	};

	public static void main(String[] args) {
		String date = format.get().format(new java.util.Date());
		System.out.println(date);

		int number = random.get().nextInt(10);
		System.out.println(number);

		// jdk 1.7 新增了一个java.util.concurrent.ThreadLocalRandom类
		number = ThreadLocalRandom.current().nextInt();
		System.out.println(number);
	}
}
